<template>
      <div class="user-audit">
            <el-card>
                  <template #header>
                        <div class="header-container">
                              <span class="header-title">用户注册审核</span>
                              <el-button type="info" size="small" @click="openGlobalHistory">查看全部审核记录</el-button>
                        </div>
                  </template>

                  <el-table :data="userList" style="width: 100%" v-loading="loading" max-height="600"
                        :header-cell-style="{ background: '#f5f7fa' }">
                        <el-table-column prop="id" label="ID" width="80" />
                        <el-table-column prop="username" label="用户名" width="150" />
                        <el-table-column prop="tel" label="手机号" width="130" />
                        <el-table-column prop="email" label="邮箱" width="180" />
                        <el-table-column prop="role" label="用户类型" width="120">
                              <template #default="{ row }">{{ roleText(row.role) }}</template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态" width="100">
                              <template #default="{ row }">
                                    <el-tag :type="row.status === '1' ? 'success' : 'warning'">
                                          {{ row.status === '1' ? '已审核' : '待审核' }}
                                    </el-tag>
                              </template>
                        </el-table-column>
                        <el-table-column prop="school" label="学校" width="150" />
                        <el-table-column prop="isPoor" label="是否贫困" width="100">
                              <template #default="{ row }">{{ row.isPoor === 1 ? '是' : '否' }}</template>
                        </el-table-column>
                        <el-table-column label="贫困证明材料" width="200">
                              <template #default="{ row }">
                                    <el-link v-if="parseImages(row.poorFile).length"
                                          @click.prevent="openImageDialog(parseImages(row.poorFile))"
                                          style="cursor: pointer; color: #409EFF">查看材料</el-link>
                                    <span v-else>无材料</span>
                              </template>
                        </el-table-column>
                        <el-table-column prop="createdTime" label="注册时间" width="180" />
                        <el-table-column label="操作" width="180" fixed="right">
                              <template #default="{ row }">
                                    <el-button type="primary" size="small" :disabled="row.status === '1'"
                                          @click="openDialog(row)">审核</el-button>
                              </template>
                        </el-table-column>
                  </el-table>
            </el-card>

            <!-- 审核弹窗 -->
            <el-dialog v-model="dialogVisible" title="用户审核" width="600px">
                  <el-descriptions :column="1" border>
                        <el-descriptions-item label="ID">{{ currentUser?.id }}</el-descriptions-item>
                        <el-descriptions-item label="用户编号">{{ currentUser?.indetifier }}</el-descriptions-item>
                        <el-descriptions-item label="用户名">{{ currentUser?.username }}</el-descriptions-item>
                        <el-descriptions-item label="手机号">{{ currentUser?.tel }}</el-descriptions-item>
                        <el-descriptions-item label="邮箱">{{ currentUser?.email }}</el-descriptions-item>
                        <el-descriptions-item label="用户类型">{{ roleText(currentUser?.role) }}</el-descriptions-item>
                        <el-descriptions-item label="学校">{{ currentUser?.school }}</el-descriptions-item>
                        <el-descriptions-item label="是否贫困">{{ currentUser?.isPoor === 1 ? '是' : '否'
                        }}</el-descriptions-item>
                        <el-descriptions-item label="贫困证明材料">
                              <el-link v-if="evidenceImages.length" @click.prevent="openImageDialog(evidenceImages)"
                                    style="cursor: pointer; color: #409EFF">查看材料</el-link>
                              <span v-else>无材料</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="状态">{{ currentUser?.status === '1' ? '已审核' : '待审核'
                        }}</el-descriptions-item>
                        <el-descriptions-item label="注册时间">{{ currentUser?.createdTime }}</el-descriptions-item>
                        <el-descriptions-item label="更新时间">{{ currentUser?.updateTiem }}</el-descriptions-item>
                  </el-descriptions>

                  <el-form :model="auditForm" label-width="100px" class="mt-4">
                        <!-- <el-form-item label="审核意见">
                                    <el-input v-model="auditForm.auditOpinion" type="textarea" rows="3" />
                              </el-form-item> -->
                        <el-form-item>
                              <el-button type="success" @click="submitAudit('1')">通过</el-button>
                              <el-button type="danger" @click="submitAudit('0')">拒绝</el-button>
                        </el-form-item>
                  </el-form>
            </el-dialog>

            <!-- 图片查看弹窗 -->
            <el-dialog v-model="imageDialogVisible" title="查看材料" width="80%" :before-close="handleImageDialogClose"
                  center>
                  <div class="image-scroll-box" style="text-align:center;">
                        <el-image v-for="(img, index) in evidenceImages" :key="index" :src="img" fit="contain"
                              style="max-height: 60vh; max-width: 100%; margin-bottom: 15px;"
                              :preview-src-list="evidenceImages" />
                  </div>
            </el-dialog>

            <!-- 全部审核记录弹窗 -->
            <el-dialog v-model="globalHistoryDialogVisible" title="全部审核记录" width="800px">
                  <el-table :data="globalHistoryList" v-loading="globalHistoryLoading" style="width: 100%">
                        <el-table-column prop="id" label="记录ID" width="80" />
                        <el-table-column prop="userId" label="用户ID" width="120" />
                        <el-table-column prop="status" label="状态" width="100" />
                        <el-table-column prop="auditOpinion" label="审核意见" />
                        <el-table-column prop="auditorId" label="审核人ID" width="120" />
                        <el-table-column prop="auditTime" label="审核时间" width="180" />
                  </el-table>
            </el-dialog>
      </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import type { UserInfo } from '@/interface/UserInfo'


const userList = ref<UserInfo[]>([])
const loading = ref(false)

const dialogVisible = ref(false)
const currentUser = ref<UserInfo | null>(null)

const auditForm = ref({
      auditOpinion: '',
})

const imageDialogVisible = ref(false)
const evidenceImages = ref<string[]>([])

const globalHistoryDialogVisible = ref(false)
const globalHistoryList = ref<any[]>([])
const globalHistoryLoading = ref(false)

function roleText(role: string | undefined) {
      switch (role) {
            case '1':
                  return '学生'
            case '2':
                  return '用工部门'
            case '3':
                  return '部门审核'
            default:
                  return '未知'
      }
}

function parseImages(poorFile: string | null | undefined): string[] {
      if (!poorFile) return []
      return poorFile.split(',').filter(s => s.trim() !== '')
}

async function fetchUserList() {
      loading.value = true
      try {
            const res = await axios.get('/api/institute/registerUser') // 只查待审核
            userList.value = res.data.data || []
      } catch {
            ElMessage.error('获取用户列表失败')
      } finally {
            loading.value = false
      }
}

function openDialog(user: UserInfo) {
      currentUser.value = user
      auditForm.value.auditOpinion = ''
      evidenceImages.value = parseImages(user.poorFile)
      dialogVisible.value = true
}

async function submitAudit(status: string) {
      if (!currentUser.value) return
      try {
            await axios.post('/api/institute/userAudit', {
                  id: currentUser.value.id,
                  status
            })
            ElMessage.success(status === '1' ? '审核通过' : '审核拒绝')
            dialogVisible.value = false
            fetchUserList()
      } catch {
            ElMessage.error('审核操作失败')
      }
}

function openImageDialog(images: string[]) {
      evidenceImages.value = images
      imageDialogVisible.value = true
}

function handleImageDialogClose(done: () => void) {
      evidenceImages.value = [];
      done(); // 调用done来关闭弹窗
}


async function openGlobalHistory() {
      globalHistoryDialogVisible.value = true
      globalHistoryLoading.value = true
      try {
            const res = await axios.get('/api/user/auditHistory')
            globalHistoryList.value = res.data || []
      } catch {
            ElMessage.error('加载审核记录失败')
      } finally {
            globalHistoryLoading.value = false
      }
}

// 页面初始化加载列表
fetchUserList()
</script>

<style scoped>
.image-scroll-box {
      max-height: 60vh;
      overflow-y: auto;
      padding: 10px;
      text-align: center;
}

.header-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
}

.header-title {
      font-size: 1.2rem;
      font-weight: 600;
}
</style>
